<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard - Speakr</title>
    <link rel="icon" href="{{ url_for('static', filename='img/favicon.svg') }}" type="image/svg+xml">
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        /* Dark Mode CSS Variables */
        :root {
            /* Light mode variables */
            --bg-primary: #f3f4f6; /* gray-100 */
            --bg-secondary: #ffffff; /* white */
            --bg-tertiary: #f9fafb; /* gray-50 */
            --bg-accent: #dbeafe; /* blue-100 */
            --bg-accent-hover: #bfdbfe; /* blue-200 */
            --bg-button: #2563eb; /* blue-600 */
            --bg-button-hover: #1d4ed8; /* blue-700 */
            --bg-danger: #dc2626; /* red-600 */
            --bg-danger-hover: #b91c1c; /* red-700 */
            --bg-danger-light: #fee2e2; /* red-100 */
            --bg-info-light: #dbeafe; /* blue-100 */
            --bg-warn-light: #fef3c7; /* amber-100 */
            --bg-success-light: #d1fae5; /* green-100 */
            --bg-pending-light: #f5f5f4; /* stone-100 */
            --bg-input: #ffffff; /* white */

            --text-primary: #1f2937; /* gray-800 */
            --text-secondary: #374151; /* gray-700 */
            --text-muted: #6b7280; /* gray-500 */
            --text-light: #9ca3af; /* gray-400 */
            --text-accent: #1d4ed8; /* blue-700 */
            --text-button: #ffffff; /* white */
            --text-danger: #b91c1c; /* red-700 */
            --text-danger-strong: #991b1b; /* red-800 */
            --text-info-strong: #1e40af; /* blue-800 */
            --text-warn-strong: #92400e; /* amber-800 */
            --text-success-strong: #065f46; /* green-800 */
            --text-pending-strong: #44403c; /* stone-700 */

            --border-primary: #e5e7eb; /* gray-200 */
            --border-secondary: #d1d5db; /* gray-300 */
            --border-accent: #93c5fd; /* blue-300 */
            --border-danger: #f87171; /* red-400 */
            --border-focus: #3b82f6; /* blue-500 */
            --ring-focus: #bfdbfe; /* blue-200 */
        }

        .dark {
            /* Dark mode variables */
            --bg-primary: #111827; /* gray-900 */
            --bg-secondary: #1f2937; /* gray-800 */
            --bg-tertiary: #374151; /* gray-700 */
            --bg-accent: #1e3a8a; /* blue-900 */
            --bg-accent-hover: #1e40af; /* blue-800 */
            --bg-button: #2563eb; /* blue-600 */
            --bg-button-hover: #3b82f6; /* blue-500 */
            --bg-danger: #dc2626; /* red-600 */
            --bg-danger-hover: #ef4444; /* red-500 */
            --bg-danger-light: #7f1d1d; /* red-900 */
            --bg-info-light: #1e3a8a; /* blue-900 */
            --bg-warn-light: #78350f; /* amber-900 */
            --bg-success-light: #064e3b; /* green-900 */
            --bg-pending-light: #292524; /* stone-800 */
            --bg-input: #374151; /* gray-700 */

            --text-primary: #f3f4f6; /* gray-100 */
            --text-secondary: #d1d5db; /* gray-300 */
            --text-muted: #9ca3af; /* gray-400 */
            --text-light: #6b7280; /* gray-500 */
            --text-accent: #60a5fa; /* blue-400 */
            --text-button: #ffffff; /* white */
            --text-danger: #f87171; /* red-400 */
            --text-danger-strong: #fca5a5; /* red-300 */
            --text-info-strong: #93c5fd; /* blue-300 */
            --text-warn-strong: #fcd34d; /* amber-300 */
            --text-success-strong: #6ee7b7; /* green-300 */
            --text-pending-strong: #d6d3d1; /* stone-300 */

            --border-primary: #374151; /* gray-700 */
            --border-secondary: #4b5563; /* gray-600 */
            --border-accent: #1d4ed8; /* blue-700 */
            --border-danger: #ef4444; /* red-500 */
            --border-focus: #3b82f6; /* blue-500 */
            --ring-focus: #1e40af; /* blue-800 */
        }

        html {
            background-color: var(--bg-primary); 
            color: var(--text-primary); 
            transition: background-color 0.3s, color 0.3s; 
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
        }
        html, body { height: 100%; margin: 0; }
        .custom-scrollbar::-webkit-scrollbar { width: 6px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: var(--scrollbar-track); border-radius: 12px; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: var(--scrollbar-thumb); border-radius: 12px; }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: var(--scrollbar-thumb-hover); }
    </style>
</head>
<body class="bg-[var(--bg-primary)] text-[var(--text-primary)]">
    <div id="app" class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col min-h-screen">
        <header class="flex justify-between items-center mb-6 pb-4 border-b border-[var(--border-primary)]">
            <h1 class="text-3xl font-bold text-[var(--text-primary)]">
                <a href="{{ url_for('index') }}" class="flex items-center">
                    <img src="{{ url_for('static', filename='img/favicon.svg') }}" alt="Speakr Logo" class="h-9 w-9 mr-2">
                    Speakr
                </a>
            </h1>
            <div class="flex items-center space-x-2">
                <button @click="toggleDarkMode" class="p-2 rounded-full text-[var(--text-muted)] hover:bg-[var(--bg-tertiary)] dark:text-gray-400 dark:hover:bg-gray-700 transition-colors duration-200" :title="isDarkMode ? 'Switch to Light Mode' : 'Switch to Dark Mode'">
                    <i :class="isDarkMode ? 'fas fa-sun' : 'fas fa-moon'"></i>
                </button>
                <div class="relative">
                    <button @click="isUserMenuOpen = !isUserMenuOpen" class="flex items-center px-3 py-2 border border-[var(--border-secondary)] rounded-lg text-[var(--text-secondary)] hover:text-[var(--text-accent)] focus:outline-none">
                        <i class="fas fa-user-shield mr-2"></i>
                        <span>{{ current_user.username }}</span>
                        <i class="fas fa-chevron-down ml-2"></i>
                    </button>
                    <div v-if="isUserMenuOpen" class="absolute right-0 mt-2 w-48 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg shadow-lg z-10">
                        <a href="{{ url_for('index') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">
                            <i class="fas fa-home mr-2"></i> Home
                        </a>
                        <a href="{{ url_for('account') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">
                            <i class="fas fa-user mr-2"></i> Account
                        </a>
                        <a href="{{ url_for('admin') }}" class="block px-4 py-2 text-[var(--text-accent)] bg-[var(--bg-accent)]">
                            <i class="fas fa-user-shield mr-2"></i> Admin
                        </a>
                        <a href="{{ url_for('logout') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-danger)]">
                            <i class="fas fa-sign-out-alt mr-2"></i> Logout
                        </a>
                    </div>
                </div>
            </div>
        </header>

        <main class="flex-grow">
            <div class="bg-[var(--bg-secondary)] p-6 rounded-xl shadow-lg border border-[var(--border-primary)]">
                <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-6">Admin Dashboard</h2>
                
                {% with messages = get_flashed_messages(with_categories=true) %}
                    {% if messages %}
                        {% for category, message in messages %}
                            <div class="mb-4 p-3 rounded-lg {% if category == 'success' %}bg-[var(--bg-success-light)] text-[var(--text-success-strong)]{% elif category == 'danger' %}bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]{% else %}bg-[var(--bg-info-light)] text-[var(--text-info-strong)]{% endif %}">
                                {{ message }}
                            </div>
                        {% endfor %}
                    {% endif %}
                {% endwith %}
                
                <!-- Tabs -->
                <div class="border-b border-[var(--border-primary)] mb-6">
                    <nav class="-mb-px flex space-x-8" aria-label="Tabs">
                        <button @click="activeTab = 'users'" 
                                :class="activeTab === 'users' ? 'border-[var(--border-focus)] text-[var(--text-accent)]' : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'"
                                class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
                            <i class="fas fa-users mr-2"></i> User Management
                        </button>
                        <button @click="activeTab = 'stats'" 
                                :class="activeTab === 'stats' ? 'border-[var(--border-focus)] text-[var(--text-accent)]' : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'"
                                class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
                            <i class="fas fa-chart-bar mr-2"></i> System Statistics
                        </button>
                    </nav>
                </div>
                
                <!-- User Management Tab -->
                <div v-show="activeTab === 'users'">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="text-lg font-medium text-[var(--text-secondary)]">User Management</h3>
                        <button @click="showAddUserModal = true" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg shadow hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] focus:ring-offset-2 transition duration-150 ease-in-out">
                            <i class="fas fa-user-plus mr-2"></i> Add User
                        </button>
                    </div>
                    
                    <!-- Search and Filter -->
                    <div class="mb-4 flex">
                        <div class="relative flex-grow">
                            <input type="text" v-model="userSearchQuery" placeholder="Search users..." class="w-full px-4 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                            <button v-if="userSearchQuery" @click="userSearchQuery = ''" class="absolute right-3 top-2.5 text-[var(--text-muted)] hover:text-[var(--text-secondary)]">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                    
                    <!-- Users Table -->
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-[var(--border-primary)]">
                            <thead class="bg-[var(--bg-tertiary)]">
                                <tr>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">ID</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Username</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Email</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Admin</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Recordings</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Storage Used</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="bg-[var(--bg-secondary)] divide-y divide-[var(--border-primary)]">
                                <tr v-for="user in filteredUsers" :key="user.id" class="hover:bg-[var(--bg-tertiary)]">
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">${ user.id }</td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-[var(--text-primary)]">${ user.username }</td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">${ user.email }</td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">
                                        <span v-if="user.is_admin" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-[var(--bg-success-light)] text-[var(--text-success-strong)]">Yes</span>
                                        <span v-else class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-[var(--bg-pending-light)] text-[var(--text-pending-strong)]">No</span>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">${ user.recordings_count }</td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">${ formatFileSize(user.storage_used) }</td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">
                                        <div class="flex space-x-2">
                                            <button @click="editUser(user)" class="text-[var(--text-accent)] hover:text-[var(--text-accent-hover)]" title="Edit User">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button @click="toggleAdminStatus(user)" :class="user.is_admin ? 'text-[var(--text-warn-strong)]' : 'text-[var(--text-info-strong)]'" :title="user.is_admin ? 'Remove Admin' : 'Make Admin'">
                                                <i class="fas" :class="user.is_admin ? 'fa-user-minus' : 'fa-user-shield'"></i>
                                            </button>
                                            <button @click="confirmDeleteUser(user)" class="text-[var(--text-danger)] hover:text-[var(--text-danger-hover)]" title="Delete User">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <tr v-if="filteredUsers.length === 0">
                                    <td colspan="7" class="px-6 py-4 text-center text-sm text-[var(--text-muted)]">
                                        <div v-if="isLoadingUsers">
                                            <i class="fas fa-spinner fa-spin mr-2"></i> Loading users...
                                        </div>
                                        <div v-else>
                                            No users found.
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <!-- System Statistics Tab -->
                <div v-show="activeTab === 'stats'">
                    <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-4">System Statistics</h3>
                    
                    <!-- Summary Cards -->
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                        <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">
                            <div class="flex items-center">
                                <div class="p-3 rounded-full bg-[var(--bg-info-light)] text-[var(--text-info-strong)]">
                                    <i class="fas fa-users text-xl"></i>
                                </div>
                                <div class="ml-4">
                                    <p class="text-sm font-medium text-[var(--text-muted)]">Total Users</p>
                                    <p class="text-2xl font-semibold text-[var(--text-primary)]">${ stats.total_users }</p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">
                            <div class="flex items-center">
                                <div class="p-3 rounded-full bg-[var(--bg-success-light)] text-[var(--text-success-strong)]">
                                    <i class="fas fa-file-audio text-xl"></i>
                                </div>
                                <div class="ml-4">
                                    <p class="text-sm font-medium text-[var(--text-muted)]">Total Recordings</p>
                                    <p class="text-2xl font-semibold text-[var(--text-primary)]">${ stats.total_recordings }</p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">
                            <div class="flex items-center">
                                <div class="p-3 rounded-full bg-[var(--bg-warn-light)] text-[var(--text-warn-strong)]">
                                    <i class="fas fa-database text-xl"></i>
                                </div>
                                <div class="ml-4">
                                    <p class="text-sm font-medium text-[var(--text-muted)]">Total Storage Used</p>
                                    <p class="text-2xl font-semibold text-[var(--text-primary)]">${ formatFileSize(stats.total_storage) }</p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">
                            <div class="flex items-center">
                                <div class="p-3 rounded-full bg-[var(--bg-accent)] text-[var(--text-accent)]">
                                    <i class="fas fa-comments text-xl"></i>
                                </div>
                                <div class="ml-4">
                                    <p class="text-sm font-medium text-[var(--text-muted)]">Total Queries</p>
                                    <p class="text-2xl font-semibold text-[var(--text-primary)]">${ stats.total_queries }</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Status Distribution -->
                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                        <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">
                            <h4 class="text-md font-medium text-[var(--text-secondary)] mb-3">Recording Status Distribution</h4>
                            <div class="grid grid-cols-2 gap-4">
                                <div class="text-center p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm">
                                    <span class="block text-2xl font-bold text-[var(--text-success-strong)]">${ stats.completed_recordings }</span>
                                    <span class="block text-sm text-[var(--text-muted)]">Completed</span>
                                </div>
                                <div class="text-center p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm">
                                    <span class="block text-2xl font-bold text-[var(--text-warn-strong)]">${ stats.processing_recordings }</span>
                                    <span class="block text-sm text-[var(--text-muted)]">Processing</span>
                                </div>
                                <div class="text-center p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm">
                                    <span class="block text-2xl font-bold text-[var(--text-pending-strong)]">${ stats.pending_recordings }</span>
                                    <span class="block text-sm text-[var(--text-muted)]">Pending</span>
                                </div>
                                <div class="text-center p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm">
                                    <span class="block text-2xl font-bold text-[var(--text-danger-strong)]">${ stats.failed_recordings }</span>
                                    <span class="block text-sm text-[var(--text-muted)]">Failed</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">
                            <h4 class="text-md font-medium text-[var(--text-secondary)] mb-3">Top Users by Storage</h4>
                            <div class="space-y-3">
                                <div v-for="user in stats.top_users" :key="user.id" class="flex justify-between items-center p-2 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)]">
                                    <div class="flex items-center">
                                        <i class="fas fa-user text-[var(--text-accent)] mr-2"></i>
                                        <span class="text-sm font-medium text-[var(--text-primary)]">${ user.username }</span>
                                    </div>
                                    <div class="text-sm text-[var(--text-secondary)]">
                                        <span class="font-medium">${ formatFileSize(user.storage_used) }</span>
                                        <span class="text-[var(--text-muted)] ml-2">(${ user.recordings_count} recordings)</span>
                                    </div>
                                </div>
                                <div v-if="stats.top_users.length === 0" class="text-center text-sm text-[var(--text-muted)] p-2">
                                    No data available
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>

        <footer class="text-center py-4 mt-8 text-xs text-[var(--text-light)] border-t border-[var(--border-primary)]">
            Speakr &copy; {{ now.year }}
        </footer>
        
        <!-- Add User Modal -->
        <div v-if="showAddUserModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
            <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-md">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-xl font-semibold text-[var(--text-primary)]">Add New User</h3>
                    <button @click="showAddUserModal = false" class="text-[var(--text-muted)] hover:text-[var(--text-secondary)]">&times;</button>
                </div>
                <form @submit.prevent="addUser">
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Username</label>
                        <input v-model="newUser.username" type="text" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Email</label>
                        <input v-model="newUser.email" type="email" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Password</label>
                        <input v-model="newUser.password" type="password" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Confirm Password</label>
                        <input v-model="newUser.confirmPassword" type="password" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                    </div>
                    <div class="mb-4 flex items-center">
                        <input v-model="newUser.isAdmin" type="checkbox" id="isAdmin" class="rounded border-[var(--border-secondary)] text-[var(--text-accent)] focus:ring-[var(--border-focus)]">
                        <label for="isAdmin" class="ml-2 text-sm text-[var(--text-secondary)]">Admin User</label>
                    </div>
                    <div class="flex justify-end space-x-3">
                        <button type="button" @click="showAddUserModal = false" class="px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-tertiary)]">Cancel</button>
                        <button type="submit" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)]">Add User</button>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Edit User Modal -->
        <div v-if="showEditUserModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
            <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-md">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-xl font-semibold text-[var(--text-primary)]">Edit User</h3>
                    <button @click="showEditUserModal = false" class="text-[var(--text-muted)] hover:text-[var(--text-secondary)]">&times;</button>
                </div>
                <form @submit.prevent="updateUser">
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Username</label>
                        <input v-model="editingUser.username" type="text" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Email</label>
                        <input v-model="editingUser.email" type="email" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">New Password (leave blank to keep current)</label>
                        <input v-model="editingUser.password" type="password" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
                    </div>
                    <div class="mb-4 flex items-center">
                        <input v-model="editingUser.is_admin" type="checkbox" id="editIsAdmin" class="rounded border-[var(--border-secondary)] text-[var(--text-accent)] focus:ring-[var(--border-focus)]">
                        <label for="editIsAdmin" class="ml-2 text-sm text-[var(--text-secondary)]">Admin User</label>
                    </div>
                    <div class="flex justify-end space-x-3">
                        <button type="button" @click="showEditUserModal = false" class="px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-tertiary)]">Cancel</button>
                        <button type="submit" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)]">Update User</button>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Delete User Confirmation Modal -->
        <div v-if="showDeleteUserModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
            <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-md">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-xl font-semibold text-[var(--text-primary)]">Confirm Delete</h3>
                    <button @click="showDeleteUserModal = false" class="text-[var(--text-muted)] hover:text-[var(--text-secondary)]">&times;</button>
                </div>
                <p class="mb-4 text-[var(--text-secondary)]">Are you sure you want to delete the user <span class="font-semibold">${ userToDelete?.username }</span>? This action cannot be undone.</p>
                <div class="flex justify-end space-x-3">
                    <button @click="showDeleteUserModal = false" class="px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-tertiary)]">Cancel</button>
                    <button @click="deleteUser" class="px-4 py-2 bg-[var(--bg-danger)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-danger-hover)]">Delete User</button>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        const { createApp, ref, computed, onMounted, watch } = Vue
        
        createApp({
            setup() {
                // State
                const activeTab = ref('users');
                const users = ref([]);
                const stats = ref({
                    total_users: 0,
                    total_recordings: 0,
                    total_storage: 0,
                    total_queries: 0,
                    completed_recordings: 0,
                    processing_recordings: 0,
                    pending_recordings: 0,
                    failed_recordings: 0,
                    top_users: []
                });
                const isLoadingUsers = ref(true);
                const userSearchQuery = ref('');
                const isDarkMode = ref(false);
                const isUserMenuOpen = ref(false);
                
                // Modal state
                const showAddUserModal = ref(false);
                const showEditUserModal = ref(false);
                const showDeleteUserModal = ref(false);
                const newUser = ref({
                    username: '',
                    email: '',
                    password: '',
                    confirmPassword: '',
                    isAdmin: false
                });
                const editingUser = ref(null);
                const userToDelete = ref(null);
                
                // Computed properties
                const filteredUsers = computed(() => {
                    if (!userSearchQuery.value) return users.value;
                    
                    const query = userSearchQuery.value.toLowerCase();
                    return users.value.filter(user => 
                        user.username.toLowerCase().includes(query) || 
                        user.email.toLowerCase().includes(query)
                    );
                });
                
                // Methods
                const loadUsers = async () => {
                    isLoadingUsers.value = true;
                    try {
                        const response = await fetch('/admin/users');
                        if (!response.ok) throw new Error('Failed to load users');
                        
                        const data = await response.json();
                        users.value = data;
                    } catch (error) {
                        console.error('Error loading users:', error);
                        // Show error notification
                    } finally {
                        isLoadingUsers.value = false;
                    }
                };
                
                const loadStats = async () => {
                    try {
                        const response = await fetch('/admin/stats');
                        if (!response.ok) throw new Error('Failed to load statistics');
                        
                        const data = await response.json();
                        stats.value = data;
                    } catch (error) {
                        console.error('Error loading statistics:', error);
                        // Show error notification
                    }
                };
                
                const addUser = async () => {
                    if (newUser.value.password !== newUser.value.confirmPassword) {
                        alert('Passwords do not match');
                        return;
                    }
                    
                    try {
                        const response = await fetch('/admin/users', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                username: newUser.value.username,
                                email: newUser.value.email,
                                password: newUser.value.password,
                                is_admin: newUser.value.isAdmin
                            })
                        });
                        
                        if (!response.ok) {
                            const errorData = await response.json();
                            throw new Error(errorData.error || 'Failed to add user');
                        }
                        
                        // Reset form and close modal
                        newUser.value = {
                            username: '',
                            email: '',
                            password: '',
                            confirmPassword: '',
                            isAdmin: false
                        };
                        showAddUserModal.value = false;
                        
                        // Reload users
                        await loadUsers();
                        await loadStats();
                        
                    } catch (error) {
                        console.error('Error adding user:', error);
                        alert(error.message);
                    }
                };
                
                const editUser = (user) => {
                    editingUser.value = { ...user, password: '' };
                    showEditUserModal.value = true;
                };
                
                const updateUser = async () => {
                    try {
                        const payload = {
                            username: editingUser.value.username,
                            email: editingUser.value.email,
                            is_admin: editingUser.value.is_admin
                        };
                        
                        // Only include password if it was changed
                        if (editingUser.value.password) {
                            payload.password = editingUser.value.password;
                        }
                        
                        const response = await fetch(`/admin/users/${editingUser.value.id}`, {
                            method: 'PUT',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify(payload)
                        });
                        
                        if (!response.ok) {
                            const errorData = await response.json();
                            throw new Error(errorData.error || 'Failed to update user');
                        }
                        
                        // Close modal and reload users
                        showEditUserModal.value = false;
                        await loadUsers();
                        
                    } catch (error) {
                        console.error('Error updating user:', error);
                        alert(error.message);
                    }
                };
                
                const confirmDeleteUser = (user) => {
                    userToDelete.value = user;
                    showDeleteUserModal.value = true;
                };
                
                const deleteUser = async () => {
                    try {
                        const response = await fetch(`/admin/users/${userToDelete.value.id}`, {
                            method: 'DELETE'
                        });
                        
                        if (!response.ok) {
                            const errorData = await response.json();
                            throw new Error(errorData.error || 'Failed to delete user');
                        }
                        
                        // Close modal and reload users
                        showDeleteUserModal.value = false;
                        await loadUsers();
                        await loadStats();
                        
                    } catch (error) {
                        console.error('Error deleting user:', error);
                        alert(error.message);
                    }
                };
                
                const toggleAdminStatus = async (user) => {
                    try {
                        const response = await fetch(`/admin/users/${user.id}/toggle-admin`, {
                            method: 'POST'
                        });
                        
                        if (!response.ok) {
                            const errorData = await response.json();
                            throw new Error(errorData.error || 'Failed to toggle admin status');
                        }
                        
                        // Reload users
                        await loadUsers();
                        
                    } catch (error) {
                        console.error('Error toggling admin status:', error);
                        alert(error.message);
                    }
                };
                
                const formatFileSize = (bytes) => {
                    if (!bytes || bytes === 0) return '0 Bytes';
                    
                    const k = 1024;
                    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
                    const i = Math.floor(Math.log(bytes) / Math.log(k));
                    
                    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
                };
                
                const toggleDarkMode = () => {
                    isDarkMode.value = !isDarkMode.value;
                    if (isDarkMode.value) {
                        document.documentElement.classList.add('dark');
                        localStorage.setItem('darkMode', 'true');
                    } else {
                        document.documentElement.classList.remove('dark');
                        localStorage.setItem('darkMode', 'false');
                    }
                };
                
                // Initialize dark mode
                const initializeDarkMode = () => {
                    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
                    const savedMode = localStorage.getItem('darkMode');
                    
                    if (savedMode === 'true' || (savedMode === null && prefersDark)) {
                        isDarkMode.value = true;
                        document.documentElement.classList.add('dark');
                    } else {
                        isDarkMode.value = false;
                        document.documentElement.classList.remove('dark');
                    }
                };
                
                // Lifecycle hooks
                onMounted(() => {
                    loadUsers();
                    loadStats();
                    initializeDarkMode();
                });
                
                // Watch for tab changes to reload data
                watch(activeTab, (newTab) => {
                    if (newTab === 'users') {
                        loadUsers();
                    } else if (newTab === 'stats') {
                        loadStats();
                    }
                });
                
                return {
                    // State
                    activeTab,
                    users,
                    stats,
                    isLoadingUsers,
                    userSearchQuery,
                    isDarkMode,
                    isUserMenuOpen,
                    
                    // Modal state
                    showAddUserModal,
                    showEditUserModal,
                    showDeleteUserModal,
                    newUser,
                    editingUser,
                    userToDelete,
                    
                    // Computed
                    filteredUsers,
                    
                    // Methods
                    loadUsers,
                    loadStats,
                    addUser,
                    editUser,
                    updateUser,
                    confirmDeleteUser,
                    deleteUser,
                    toggleAdminStatus,
                    formatFileSize,
                    toggleDarkMode
                };
            },
            delimiters: ['${', '}'] // Use different delimiters to avoid conflict with Flask's Jinja2
        }).mount('#app');
    </script>
</body>
</html>
